<template>
  <BasicModal
    v-bind="$attrs"
    @register="registerModal"
    showFooter
    :title="getTitle"
    width="35%"
    @ok="handleSubmit"
  >
    <BasicForm @register="registerForm" />
  </BasicModal>
</template>
<script lang="ts" setup name="AuthorModal">
import { ref, computed, unref } from "vue";
import { BasicForm, useForm } from "/@/components/Form/index";
import { formSchema } from "./index-option";
import { BasicModal, useModalInner } from "/@/components/Modal";
import {
  getAuthorDetailApi,
  saveAuthorApi,
  updateAuthorApi,
} from "/@/api/microresource/author";
import { useMessage } from "/@/hooks/web/useMessage";

const { createMessage } = useMessage();
const emit = defineEmits(["success"]);
const getTitle = computed(() => (!unref(isUpdate) ? "新增作者" : "编辑作者"));
const isUpdate = ref(true);
const authorId = ref();

const [registerForm, { resetFields, setFieldsValue, validate }] = useForm({
  labelWidth: 80,
  schemas: formSchema,
  showActionButtonGroup: false,
  baseColProps: { lg: 24, md: 24 },
});

const [registerModal, { setModalProps, closeModal }] = useModalInner(async (data) => {
  resetFields();
  isUpdate.value = !!data?.isUpdate;
  if (unref(isUpdate)) {
    authorId.value = data.record.authorId;
    let res = await getAuthorDetailApi(authorId.value);
    setFieldsValue({
      ...res.data,
      file: [
        {
          uuid: res.data.avatar,
          name: "头像",
          url: res.data.avatar,
        },
      ],
    });
  }
  setModalProps({ confirmLoading: false });
});

async function handleSubmit() {
  try {
    const values = await validate();
    setModalProps({ confirmLoading: true });
    let res;

    if (unref(isUpdate)) {
      const param = {
        ...values,
        authorId: authorId.value,
        avatar: values.file ? values.file[0]?.uuid : "",
      };
      res = await updateAuthorApi(param);
    } else {
      const param = {
        ...values,
        avatar: values.file ? values.file[0]?.uuid : "",
      };
      res = await saveAuthorApi(param);
    }
    createMessage.success(res.msg);
    closeModal();
    emit("success");
  } finally {
    setModalProps({ confirmLoading: false });
  }
}
</script>
